import {Component} from '@angular/core';
import {Events, PopoverController, ViewController, NavController} from 'ionic-angular';
import {MachineDetailPage} from "../machine-detail/machine-detail";
import {Machine} from "../../providers/machine";
import {AppData} from "../../providers/app-data";
import {Response} from "@angular/http";

@Component({
  template: `
    <ion-list>
      <button ion-item (click)="close()">添加新机器</button>
    </ion-list>
  `
})
class PopoverPage {

  constructor(public events: Events, public viewCtrl: ViewController, public navCtrl: NavController) {
  }

  close() {
    this.viewCtrl.dismiss().then(()=> {
      var newMachine: any;
      newMachine = new Machine();
      newMachine.id = "";
      newMachine.name = "新机器";
      newMachine.isOnline = false;
      newMachine.params = "";
      newMachine.startTime = "";
      newMachine.endTime = "";
      newMachine.client = "";
      this.events.publish('addMachine:add', newMachine);
    });

  }
}


@Component({
  templateUrl: 'build/pages/machine-manage/machine-manage.html'
})
export class MachineManagePage {
  machineList = [];

  constructor(public popoverCtrl: PopoverController, public navCtrl: NavController, public events: Events, public appData: AppData) {
    this.listenAddMachineEvents();
  }

  listenAddMachineEvents() {
    this.events.subscribe('addMachine:add', (userArray) => {
      this.goToMachineDetail(userArray[0]);
    });
  }

  goToMachineDetail(machine) {
    this.navCtrl.push(MachineDetailPage, machine);
  }

  ionViewDidEnter() {
    this.appData.getMachineList().then((res: Response) => {
      this.machineList = res.json().result;
    });
  }

  presentPopover(event) {
    let popover = this.popoverCtrl.create(PopoverPage);
    popover.present({ev: event});
  }
}
